package com.rupertjones.globalcron;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

import java.io.IOException;
import java.io.InputStream;
import java.net.UnknownHostException;
import java.util.Properties;

public class PropertyPlaceholderForTestConfiguration extends PropertyPlaceholderConfigurer {

    private static final Logger LOG = Logger.getLogger(PropertyPlaceholderForTestConfiguration.class);
    private volatile String propertiesLocation;

    public PropertyPlaceholderForTestConfiguration(String fileLocation) {
        this.propertiesLocation = fileLocation;
    }

    protected String resolvePlaceholder(String placeholder, Properties props) {

        try {
            Properties properties = new Properties();

            InputStream is = this.getClass().getResourceAsStream(propertiesLocation);
            properties.load(is);
            String property = properties.getProperty(placeholder);

            if (property == null) {
                throw new RuntimeException("Couldn't find property [" + placeholder + "]. Returning an empty string.");
            }

            LOG.info("Loading property [" + placeholder + "] with value [" + property + "]");
            return property;
        } catch (UnknownHostException e) {
            LOG.error(e);
        } catch (IOException e) {
            LOG.error(e);
        }
        LOG.error("Could not find configuration property [" + placeholder + "]");
        return null;
    }
}
